// 发布订阅模式
class Publisher {
  constructor() {
    this.map = new Map();
  }
  on(key, callback) {
    let arr = this.map.get(key) || [];
    arr.push(callback);
    this.map.set(key, arr);
  }
  emit(key, data = {}) {
    if (this.map.has(key)) {
      this.map.get(key).forEach((item) => {
        item.call(this, data);
      });
    }
  }
  clear() {
    this.map.clear();
  }
}

let publisher = new Publisher();

// 页面扩展
const oldPage = Page;
Page = function (params) {
  const { onLoad, onShow, onReady } = params;
  let isPermissions = false;

  params.onLoad = function (p) {
    if (havePermissions(isPermissions)) {
      onLoad?.call(this, p);
    }
    else {
      publisher.on("permissions", () => {
        isPermissions = true;
        onLoad?.call(this, p);
      });
      publisher.on("permissions", () => {
        isPermissions = true;
        onShow?.call(this, p);
      });
      publisher.on("permissions", () => {
        isPermissions = true;
        onReady?.call(this, p);
      });
    }
  };

  params.onShow = function (p) {
    if (havePermissions(isPermissions)) {
      onShow?.call(this, p);
    }
  };

  params.onReady = function (p) {
    if (havePermissions(isPermissions)) {
      onReady?.call(this, p);
    }
  };

  params.onHide = function () {
    publisher.clear();
  };

  params.onUnload = function () {
    publisher.clear();
  };

  return oldPage(params);
};

function havePermissions(isPermissions) {
  if (isPermissions && publisher?.map?.size === 0) {
    return true;
  }

  return false;
}

module.exports = {
  publisherPermissions: publisher,
};
